import { action, observable, transaction } from 'mobx';
import { storage, util, crypto } from '../utils';
import { userService } from '../server';
import { config } from '../config';

/**
 * @desc 存放外部传入的props数据
 */
console.log('token', crypto.decrypt(storage.local.get('token')));
class User {
  token = crypto.decrypt(storage.local.get('token')); // 外部传入的参数
  @observable info = null; // 外部传入的参数

  /**
   * 设置用户信息
   * @param {*} info
   * @param {*} token
   */
  @action
  setUserInfo(info) {
    this.info = info;
  }

  @action
  getUserInfo() {
    return this.info;
  }

  @action
  getToken() {
    return crypto.decrypt(this.token);
  }

  @action
  setToken(token) {
    token = crypto.encrypt(token);
    this.token = token;
    storage.local.set('token', token);
  }

  @action
  updateUserInfo(values) {
    transaction(() => {
      for (let key in values) {
        this.info[key] = values[key];
      }
    });
  }

  @action
  logout = async () => {
    await userService.logout();
    user.clearUserInfo();
    util.history.push(config.unLoginLinkTo);
  };

  @action
  clearUserInfo() {
    transaction(() => {
      this.info = null;
      this.token = null;
    });
    storage.local.remove('token');
  }
}

export const user = new User();
